import { loadJS } from '@/utils/utils';
import { Spin } from 'antd';
import React, { useEffect, useState } from 'react';
import styles from './index.less';

/**
 * content  编辑器中的内容
 * onChange 编辑器内容修改触发的事件，返回两个值，第一个为当前content，第二个为内容中第一个图片的地址，若不存在图片则为空
 * editConfig 可自定义配置编辑器工具栏
 * disabled 是否可编辑，默认false
 * api 上传图片的接口，默认值为/api/help/weUpload
 */
export interface CkeditorProps {
  content: string;
  onChange?: (content: any, firsturl: string) => void;
  onUploadChange?: () => void;
  editConfig: any; // 额外配置，新增额外功能后，需要将新增插件集成到ckeditor.js中重新build更换
  disabled?: boolean;
  api?: string;
  style?: object;
}

const Page = (props: any) => {
  const { content: _content, disabled = false } = props;

  const [loadedLibrary, setLoadedLibrary] = useState(false);

  const [content, setContent] = useState(_content);

  useEffect(() => {
    (async () => {
      const { state }: any = await loadJS(`${BASE}js/ckeditor.js`);
      if (state !== 'success') {
        return;
      }
      setLoadedLibrary(true);
    })();
  }, []);

  useEffect(() => {
    setContent(_content);
  }, [_content]);

  return (
    <div className={disabled ? styles.editordisabled : styles.editor}>
      {loadedLibrary ? (
        <></>
      ) : (
        <div
          style={{
            width: '100%',
            height: '100%',
            textAlign: 'center',
            background: 'rgba(0, 0, 0, 0.01)',
            borderRadius: '4px',
            marginBottom: '20px',
            padding: '30px 50px',
            margin: '20px 0',
          }}
        >
          <Spin />
        </div>
      )}
    </div>
  );
};
export default Page;
